package com.xing.servlet;

import com.xing.domain.User;
import com.xing.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 静，谦虚谨慎，心胸宽广容纳所有好的坏的、先苦后甜
 * day38web2
 * 2021/4/28 15:51
 */
@WebServlet(value = "/registservlet")
public class RegistServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2接收数据
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String repwd = req.getParameter("repwd");
        String email = req.getParameter("email");
        String gender = req.getParameter("gender");
        //3检验
        //3.1非空校验
        //trim() 方法用于删除字符串的头尾空白符。
        if(username==null||username.trim().length()==0){
            resp.getWriter().write("用户名不能为空");
            return;
        }
        if(pwd==null||pwd.trim().length()==0){
            resp.getWriter().write("密码不能为空");
            return;
        }
        if(!pwd.equals(repwd)){
            resp.getWriter().write("两次密码不一致");
            return;
        }
        if(email==null||email.trim().length()==0){
            resp.getWriter().write("邮箱不能为空");
            return;
        }
        //4.访问数据库层
        UserServiceImpl userService = new UserServiceImpl();
        User user = new User(null,username,pwd,email,gender,0,1,"");
        try {
            userService.regist(user);
            //重定向登录页面
            resp.sendRedirect("login.html");

        } catch (Exception e) {
            e.printStackTrace();
            req.getRequestDispatcher("/message.html").forward(req, resp);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
